<template>
    <!-- :title="`${isEdit ? '修改' : '新增'}运价表`" -->
  <el-dialog
    class="public-dialog"
    title="查看"
    width="80%"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
    destroy-on-close
  >
    <div class="h-[60vh]" v-loading="loading">
      <div v-if="id" class="flex flex-wrap my-[8px]">
        <div
          class="text-[14px] text-[var(--base-text-color)] leading-[30px] mr-[32px]"
          v-for="item in headInfo"
          :key="item.label"
        >
          <span class="text-[var(--base-sub-text-color)]"
            >{{ item.label }}：</span
          >
          <span class="text-[var(--base-text-color)]">{{
            headInfoData[item.field] || "-"
          }}</span>
        </div>
      </div>
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="optionAll"
        @optionsData="getOptions"
      >
        <template #warehouse="{ input, value }">
          <WarehouseSelect
            disabled
            multiple
            collapse-tags-tooltip
            @update:model-value="input"
            :model-value="value"
            collapse-tags
          />
        </template>
        <template #platform="{ input, value }">
          <PlatformSelect
            @update:model-value="input"
            :multiple="true"
            :model-value="value"
          />
        </template>
        <template #cost>
          <TransportCost
            ref="transportCostRef"
            :billingType="billingType"
            :data="transportData"
            :type="type"
            @changeCurrency="handleCurrency"
          />
        </template>
        <!-- <template #unilateral_max_lwh="{ value, input }">
          <Volume :value="value" @input="input" />
        </template> -->
        <!-- <template #super_unilateral_lwh="{ value, input }">
          <Volume :value="value" @input="input" />
        </template> -->
        <template #dimensional_limit>
          <Dimensional
            ref="dimensionalRef"
            :options="options"
            :data="channelTransportCostRls"
          />
        </template>
        <template #zip_code_ids="{ value, input }">
          <el-cascader
            :modelValue="value"
            @update:modelValue="input"
            :options="optionAll.zipCodeRegion"
            :props="{ multiple: true }"
            class="cascader-wrapper-style"
            collapse-tags
            collapse-tags-tooltip
            clearable
            filterable
          />
        </template>
      </VForm>
      <!-- <Attach
        ref="AttachRef"
        :options="options"
        :deliverMode="deliverModeData"
        :data="surchargeDataProps"
      /> -->
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <!-- <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button> -->
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import VForm from "@/components/Form/index.vue";
import WarehouseSelect from "@/components/WarehouseSelect/index.vue";
import Attach from "@/views/logistics-settings/channel/add/BaseInfo/Attach/index.vue";
import TransportCost from "./TransportCost/index.vue";
// import Volume from "./Volume/index.vue";
import PlatformSelect from "@/components/PlatformSelect/index.vue";
import { extractAndUniqueSecondElement } from "@/utils/tool.js";
import {
  createTransportCost,
  updateTransportCost,
  transportCostDetail,
  zipCodeRegion,
} from "../api";
import Dimensional from "./Dimensional/index";
const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  deliverMode: { type: [String, Number], default: "" },
  billingType: { type: Number, default: 1 },
  options: { type: Object, default: () => ({}) },
  channelId: { type: [String, Number], default: "" },
  type: { type: [String, Number], default: "" },
  currency: { type: String, default: "" },
});
const { options } = toRefs(props);
const emit = defineEmits(["update:modelValue", "refresh", "close"]);
function groupByMatchType(data) {
  return data.reduce((result, item) => {
    const { match_type, match_type_text, region_name, status, id } = item;
    const existingGroup = result.find(
      (group) => group.match_type === match_type
    );
    if (existingGroup) {
      existingGroup.children.push({ label: region_name, status, value: id });
    } else {
      result.push({
        value: match_type,
        match_type,
        label: match_type_text,
        children: [{ label: region_name, status, value: id }],
      });
    }

    return result;
  }, []);
}

function extractData(item) {
  // 根据实际情况提取数据，这里简单演示
  return {
    region_name: item.region_name,
    status: item.status,
    id: item.id,
  };
}

const zipCodeRegionOptions = ref([]);
const getZipCodeRegion = async () => {
  try {
    let res = await zipCodeRegion();
    if (res?.data?.length) {
      res?.data.forEach((item) => {
        if (!item.status) {
          item.disabled = true;
        }
      });
      zipCodeRegionOptions.value = groupByMatchType(res?.data || []);
    }
  } catch (error) {}
};
getZipCodeRegion();
const optionAll = computed(() => {
  return {
    ...options.value,
    zipCodeRegion: zipCodeRegionOptions.value,
  };
});
const headInfo = [
  { label: "运价文件", field: "file_name" },
  { label: "物流商", field: "logistics_name" },
  { label: "中文渠道名称", field: "channel_name" },
  { label: "运输类型", field: "transport_type_text" },
  { label: "计费类型", field: "billing_type_text" },
];

const formOption = {
  inline: true,
  labelPosition: "top",
};

const rules = {
  logistics_id: [{ required: true, message: "请选择物流商", trigger: "blur" }],
  channel_id: [
    { required: true, message: "请选择物流商渠道", trigger: "blur" },
  ],
  channel_api_id: [
    { required: true, message: "请选择渠道API", trigger: "blur" },
  ],
  time: [{ required: true, message: "请选择生效时间", trigger: "blur" }],
};
// const surchargeData = ref({
//   surcharge: [],
//   channel: {},
// });
// const surchargeDataProps = computed(() => {
//   return surchargeData.value;
// });
// watch(
//   () => surchargeData.value,
//   (val) => {
//     surchargeDataProps.value = val;
//   },
//   {
//     deep: true,
//   }
// );
const form = ref();
const transportCostRef = ref();
// const AttachRef = ref();
const model = ref({});
const loading = ref();

const costDataAll = ref([]);
const optionsData = ref({});
const getOptions = (data) => {
  optionsData.value = data;
};
const transportData = computed(() => {
  return {
    currency: model.value?.currency || null,
    costData: costDataAll.value,
  };
});
const handleCountry = async (val) => {
  let item = optionsData.value["mapCountry"]?.find(
    (n) => n.country_name === val
  );
  if (item) {
    let data = await form.value.submit();
    model.value = Object.assign({}, data, {
      destination_country: item?.country || null,
    });
    // model.value.destination_country = item?.country || null;
  }

  // model.value.arrival_address = val || null;
};
const publicStyle = { style: { width: "262px" } };
const fieldList = ref([
  { type: "title", label: "基础信息" },
  { field: "shipping_address", label: "始发地", ...publicStyle },
  {
    field: "arrival_address",
    label: "目的地",
    type: "select",
    origin: "map.country",
    options: {
      placeholder: "请选择目的地",
      valueKey: "country_name",
      labelKey: "country_name",
    },
    itemProps: {
      onChange: handleCountry,
    },
  },
  { field: "destination_country", label: "目的地二字码", ...publicStyle },
  {
    field: "goods_attrs",
    label: "货物类型",
    type: "select",
    multiple: true,
    originField: "logisticsAttributes",
    ...publicStyle,
  },
  {
    field: "zip_code_ids",
    label: "区域",
    slot: "zip_code_ids",
    // type: "select",
    // multiple: true,
    // originField: "zipCodeRegion",
    // options: {
    //   placeholder: "请选择目的地",
    //   valueKey: "id",
    //   labelKey: "region_name",
    // },
    style: { width: "300px" },
  },
  {
    field: "limit",
    label: "时效",
    type: "numberRange",
    ...publicStyle,
    placeholder: "请输入",
    suffix: "天",
  },
  { field: "count_reason", label: "抛重计算因子", ...publicStyle },
  {
    field: "platform_ids",
    label: "平台",
    ...publicStyle,
    slot: "platform",
  },
  {
    field: "time",
    label: "版本时间",
    type: "dateTimeRange",
    style: { width: "380px" },
  },
  { field: "cost", slot: "cost", full: true, style: "width: 100%" },
  { type: "br" },
  { field: "warehouse", label: "发货仓", slot: "warehouse", ...publicStyle },
  { field: "fuel_rate", label: "燃油费比率", append: "%", ...publicStyle ,itemProps: {disabled:true}},
  // {
  //   field: "unilateral_max_lwh",
  //   label: "单边最大可发长宽高",
  //   slot: "unilateral_max_lwh",
  //   ...publicStyle,
  // },
  // {
  //   field: "super_unilateral_lwh",
  //   label: "超单边长宽高",
  //   slot: "super_unilateral_lwh",
  //   ...publicStyle,
  // },
  // {
  //   field: "super_surcharge",
  //   label: "超尺寸附加费",
  //   append: "RMB",
  //   ...publicStyle,
  // },
  {
    field: "mini_bill_value",
    label: "最低计费重",
    append: "kg",
    ...publicStyle,
  },
  {
    field: "calc_fuel_mode",
    label: "是否计算燃油附加费",
    type: "select",
    originField: "channel_calc_fuel_mode",
    ...publicStyle,
    show: () => [1, 2].includes(props.billingType),
  },
  { type: "br" },
  {
    field: "dimensional_limit",
    slot: "dimensional_limit",
    full: true,
    style: "width: 100%",
  },
  { type: "br" },
  {
    field: "remark",
    label: "备注",
    type: "textarea",
    autosize: { minRows: 2, maxRows: 6 },
    full: true,
    itemStyle: { width: "100%" },
  },
]);
const deliverModeData = ref();
watch(
  () => props.id,
  (val) => {
    nextTick(() => {
      if (val) getDetail(val);
    });
  }
);
watch(
  () => [props.type, props.deliverMode],
  (val) => {
    if (props.type == "add" && props.deliverMode) {
      deliverModeData.value = props.deliverMode;
    }
  }
);
watch(
  () => props.currency,
  (val) => {
    model.value.currency = val;
  }
);
const headInfoData = ref({});
const surcharge_original = ref([]);
const cost_detail_original = ref([]);
const channelTransportCostRls = ref([]);
const getDetail = async (id) => {
  try {
    loading.value = true;
    const { data } = await transportCostDetail({ id });
    const {
      channel,
      channel_surcharge,
      channel_transport_cost_detail,
      channel_transport_cost,
      channel_transport_cost_rls,
      channel_tc_version
    } = data;
    const { max_time_limit, min_time_limit } =
      channel_transport_cost;
    const {v_start_time,v_end_time} = channel_tc_version
    let channel_transport_cost_data = {
      ...channel_transport_cost,
      limit: {
        min: min_time_limit,
        max: max_time_limit,
      },
    };
    headInfoData.value = Object.assign({}, channel, {
      file_name: channel_transport_cost.file_name,
    });
    channelTransportCostRls.value = JSON.parse(
      JSON.stringify(channel_transport_cost_rls || [])
    );

    model.value = Object.assign({}, channel_transport_cost_data, {
      currency: channel.currency,
      // inner_surcharge_zero: channel.inner_surcharge_zero,
      warehouse: channel.warehouse,
      fuel_rate: channel.fuel_rate,
      time: [v_start_time, v_end_time],
    });
    // surchargeData.value.surcharge = JSON.parse(
    //   JSON.stringify(channel_surcharge)
    // );
    // surcharge_original.value = JSON.parse(
    //   JSON.stringify(channel_surcharge || [])
    // );
    // surchargeData.value.channel = JSON.parse(JSON.stringify(channel));
    deliverModeData.value = props.deliverMode;
    costDataAll.value = channel_transport_cost_detail;
    cost_detail_original.value = JSON.parse(
      JSON.stringify(channel_transport_cost_detail)
    );
  } catch (e) {
    // surchargeData.value.surcharge = [];
    // surchargeData.value.channel = {};
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const isEdit = computed(() => {
  return !!props.id;
});
const dimensionalRef = ref();
const handleSave = async () => {
  try {
    const channel_transport_cost = await form.value.submit();
    const api = {
      edit: updateTransportCost,
      add: createTransportCost,
    };
    const { channelId } = props;
    headInfoData.value.id = Number(channelId || 0);
    // const { channel_surcharge, inner_surcharge_zero } =
    //   await AttachRef.value.submit();
    const { cost, currency } = await transportCostRef.value.submit();
    headInfoData.value.currency = currency;
    // headInfoData.value.inner_surcharge_zero = inner_surcharge_zero;
    headInfoData.value.warehouse = channel_transport_cost.warehouse;
    headInfoData.value.fuel_rate = channel_transport_cost.fuel_rate;
    channel_transport_cost.channel_id = Number(channelId || 0);
    let zip_code_ids = JSON.parse(
      JSON.stringify(channel_transport_cost.zip_code_ids || [])
    );
    let falge = zip_code_ids.some((element) => Array.isArray(element));
    let zip_code_ids_data = [];
    if (falge) {
      zip_code_ids_data = extractAndUniqueSecondElement(zip_code_ids);
    } else {
      zip_code_ids_data = zip_code_ids;
    }

    channel_transport_cost.zip_code_ids = zip_code_ids_data;
    const { limit, time } = channel_transport_cost;
    channel_transport_cost.min_time_limit = limit.min;
    channel_transport_cost.max_time_limit = limit.max;
    channel_transport_cost.start_time = time[0];
    channel_transport_cost.end_time = time[1];
    const miniBillValue = channel_transport_cost?.mini_bill_value;

    // const maxChannelTransportValue = channel_surcharge?.[0]?.max_value;
    // if (miniBillValue || miniBillValue === 0) {
    //   const warningMessage =
    //     miniBillValue > (maxChannelTransportValue ?? Infinity)
    //       ? "最低计费重不能大于第一区间最大值"
    //       : 0;

    //   if (warningMessage) {
    //     ElMessage.warning(warningMessage);
    //     return;
    //   }
    // }
    // const channel_surcharge_delete = surcharge_original.value
    //   ?.filter((item) => item?.id && item?.has_inc_attrs)
    //   ?.filter(
    //     (item) =>
    //       !channel_surcharge
    //         ?.filter((item) => item?.id && item?.has_inc_attrs)
    //         ?.some((n) => n.id === item?.id && n?.has_inc_attrs)
    //   )
    //   .map((item) => ({ ...item, is_delete: 1 }));

    // let channel_surcharge_all = [
    //   ...channel_surcharge,
    //   ...channel_surcharge_delete,
    // ];
    // let channel_surcharge_all_data = channel_surcharge_all.filter(
    //   (item) => !(!item?.id && item?.cost_attrs?.length == 0)
    // );
    // channel_surcharge_all_data.forEach((item, index) => {
    //   if (item?.id && item?.cost_attrs?.length == 0) {
    //     item.is_delete = 1;
    //   }
    // });
    const { channel_transport_cost_rls } = await dimensionalRef.value.submit();
    const cost_detail_original_delete = cost_detail_original.value
      ?.filter((item) => item?.id)
      ?.filter((item) => !cost?.some((n) => n.id === item?.id))
      .map((item) => ({ ...item, is_delete: 1 }));
    let cost_detail_original_all = [...cost_detail_original_delete, ...cost];
    const { code, message } = await api[isEdit.value ? "edit" : "add"]({
      channel: headInfoData.value,
      channel_transport_cost,
      channel_transport_cost_detail: cost_detail_original_all,

      channel_transport_cost_rls,
      // channel_surcharge: channel_surcharge_all_data,
    });
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
    handleClose(true);
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const handleCurrency = (val) => {
  if (!val) return;
  let item = fieldList.value.find((n) => n.field == "super_surcharge");
  item.append = val;
};

const handleClose = async (refresh) => {
  deliverModeData.value = null;
  // surchargeData.value.surcharge = [];
  // surchargeDataProps.value = {};
  model.value = {};
  costDataAll.value = [];
  headInfoData.value = {};
  transportCostRef.value.reset();
  await nextTick();
  form.value.resetForm();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
